define([
  'controllers/home/home',
  'controllers/sidebar/sidebarMngr',
  'text!templates/sidebar/sidebar.html',
  'text!templates/sidebar/footerWidget.html',
], function (Home, SidebarMngr, SidebarTmpl, SidebarFooterTmpl) {

    var View = Backbone.View.extend({
        el: $("body"),
        $sidebar: null,

        render: function () {
            var that = this;

            // Prepare Sidebar MainMenu Template
            var mainMenuTmpl = Handlebars.compile(SidebarTmpl);
            var menuData = {
                // pasar datos al listado del menu (si es necesario)

            };
            var menuHTML = mainMenuTmpl(menuData);

            // Prepare Sidebar FooterWidget Template
            var footerMenuTmpl = Handlebars.compile(SidebarFooterTmpl);
            var footerData = {
                
            };
            var footerHTML = footerMenuTmpl(footerData);

            // Prepare Main Template
            //var mainTmpl = Handlebars.compile(MainTmpl);

            //var data = {
            //    userName: __currentSession.userName,
            //    companyName: __currentSession.companyName
            //};

            //var html = mainTmpl(data);
            //this.$el.html(html);
            //this.$el.removeClass("login");
            
            this.$el.find("#main-menu").append(menuHTML);

            // start listen notifications for this user
            //var notify = new Notification();
            //notify.start();


            //$("#brand").click(function () {
            //    (new Home()).selectTask("summary");
            //    return false;
            //});

            //$("#topMenuBar a.btn-remove").hide();

            /* Cambiar color de app */
            //$(".theme-colors > li > span").hover(function (e) {
            //    var $el = $(this),
            //    body = $('body');
            //    body.attr("class", "").addClass("theme-" + $el.attr("class"));
            //}, function () {
            //    var $el = $(this),
            //    body = $('body');
            //    if (body.attr("data-theme") !== undefined) {
            //        body.attr("class", "").addClass(body.attr("data-theme"));
            //    } else {
            //        body.attr("class", "");
            //    }
            //}).click(function () {
            //    var $el = $(this);
            //    $("body").addClass("theme-" + $el.attr("class")).attr("data-theme", "theme-" + $el.attr("class"));
            //});
            /* FIN Cambiar color de app */

            //$("ul.user-menu a").click(function () {
            //    var code = $(this).attr("data-rel");
            //    switch (code) {
            //        case "signout":
            //            require(['models/security/session'], function (SessionModel) {
            //                (new SessionModel()).logout(function () {
            //                    location.reload();
            //                });
            //            });
            //            break;
            //    }

            //    return false;
            //});

            // get widgetlist from user preferences
            //require(['models/abmManagers/userManager'], function (UserModel) {
            //    (new UserModel()).GetUserPreference("summary_widgets", function (data) {
            //        var homeController = new Home();
            //        homeController.addWidgets(data);

            //    });
            //});


            //******************************** MAIN SIDEBAR ******************************//

            var $html = $('html');
            //var $wrapper = $('#wrapper');
            that.$sidebar = $('#sidebar');
            var $sidebar_toggle = $('.sidebar-toggle');
            var $sidebar_submenu = $('.submenu');

            function manageSidebar() {

                /* We change sidebar type on resize event */
                $(window).bind('enterBreakpoint1200', function () {
                    $html.removeClass().addClass('sidebar-large');
                    $('.sidebar-nav li.current').addClass('active');
                    $('.sidebar-nav li.current .submenu').addClass('in').height('auto');
                    $sidebar_toggle.attr('id', 'menu-medium');
                    that.$sidebar.removeClass('collapse');
                    sidebarHeight();
                    createSideScroll();
                });

                $(window).bind('enterBreakpoint768', function () {
                    $html.removeClass('sidebar-hidden').removeClass('sidebar-large').removeClass('sidebar-thin').addClass('sidebar-medium');
                    $('.sidebar-nav li.current').removeClass('active');
                    $('.sidebar-nav li.current .submenu').removeClass('in');
                    $sidebar_toggle.attr('id', 'menu-thin');
                    sidebarHeight();
                    that.$sidebar.removeClass('collapse');
                    $("#menu-right").trigger("close");
                    destroySideScroll();
                });

                $(window).bind('enterBreakpoint480', function () {
                    $html.removeClass('sidebar-medium').removeClass('sidebar-large').removeClass('sidebar-hidden').addClass('sidebar-thin');
                    $('.sidebar-nav li.current').removeClass('active');
                    $('.sidebar-nav li.current .submenu').removeClass('in');
                    that.$sidebar.removeClass('collapse');
                    sidebarHeight();
                    destroySideScroll();
                });

                $(window).bind('enterBreakpoint320', function () {
                    $html.removeClass('sidebar-medium').removeClass('sidebar-large').removeClass('sidebar-thin').addClass('sidebar-hidden');
                    sidebarHeight();
                    destroySideScroll();
                });

                /* We change sidebar type on click event */
                $(document).on("click", "#menu-large", function () {
                    $html.removeClass('sidebar-medium').removeClass('sidebar-hidden').removeClass('sidebar-thin').addClass('sidebar-large');
                    $sidebar_toggle.attr('id', 'menu-medium');
                    $('.sidebar-nav li.current').addClass('active');
                    $('.sidebar-nav li.current .submenu').addClass('in').height('auto');
                    sidebarHeight();
                    createSideScroll();
                });

                $(document).on("click", "#menu-medium", function () {
                    $html.removeClass('sidebar-hidden').removeClass('sidebar-large').removeClass('sidebar-thin').addClass('sidebar-medium');
                    $sidebar_toggle.attr('id', 'menu-thin');
                    $('.sidebar-nav li.current').removeClass('active');
                    $('.sidebar-nav li.current .submenu').removeClass('in');
                    sidebarHeight();
                    destroySideScroll();
                });

                $(document).on("click", "#menu-thin", function () {
                    $html.removeClass('sidebar-medium').removeClass('sidebar-large').removeClass('sidebar-thin').addClass('sidebar-thin');
                    $sidebar_toggle.attr('id', 'menu-large');
                    $('.sidebar-nav li.current').removeClass('active');
                    $('.sidebar-nav li.current .submenu').removeClass('in');
                    sidebarHeight();
                    if ($('body').hasClass('breakpoint-768')) $sidebar_toggle.attr('id', 'menu-medium');
                    destroySideScroll();
                });

                function destroySideScroll() {
                    that.$sidebar.mCustomScrollbar("destroy");
                }

                function createSideScroll() {
                    destroySideScroll();
                    if (!(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))) {
                        that.$sidebar.mCustomScrollbar({
                            scrollButtons: {
                                enable: false
                            },
                            autoHideScrollbar: true,
                            scrollInertia: 150,
                            theme: "light-thin",
                            advanced: {
                                updateOnContentResize: true
                            }
                        });
                    }
                }
                // handlers del menu personalizados
                that.addMenuHandlers();
            }

            /* Toggle submenu open */
            function toggleSidebarMenu() {
                var $this = $('.sidebar-nav');
                $this.find('li.active').has('ul').children('ul').addClass('collapse in');
                $this.find('li').not('.active').has('ul').children('ul').addClass('collapse');
                $this.find('li').has('ul').children('a').on('click', function (e) {
                    e.preventDefault();
                    $(this).parent('li').toggleClass('active').children('ul').collapse('toggle');
                    $(this).parent('li').siblings().removeClass('active').children('ul.in').collapse('hide');
                });
            }

            /* Adjust sidebar height */
            function sidebarHeight() {
                /* Cambie styles, no necesito esto ... TODO: BORRARLO SI TODO ANDA BIEN
                var sidebar_height;
                var mainMenuHeight = parseInt($('#main-menu').height());
                var windowHeight = parseInt($(window).height());
                var mainContentHeight = parseInt($('#main-content').height());
                if (windowHeight > mainMenuHeight && windowHeight > mainContentHeight)
                    sidebar_height = windowHeight;
                if (mainMenuHeight > windowHeight && mainMenuHeight > mainContentHeight)
                    sidebar_height = mainMenuHeight;
                if (mainContentHeight > mainMenuHeight && mainContentHeight > windowHeight)
                    sidebar_height = mainContentHeight;
                if ($html.hasClass('sidebar-large') || $html.hasClass('sidebar-hidden')) {
                    that.$sidebar.height('');
                } else {
                    that.$sidebar.height(sidebar_height);
                }
                */
            }


            /* Sidebar Statistics */
            if ($.fn.sparkline) {
                /* Sparklines can also take their values from the first argument passed to the sparkline() function */
                var myvalues1 = [13, 14, 16, 15, 11, 14, 20, 14, 12, 16, 11, 17, 19, 16];
                var myvalues2 = [14, 17, 16, 12, 18, 16, 22, 15, 14, 17, 11, 18, 11, 12];
                var myvalues3 = [18, 14, 15, 14, 15, 12, 21, 16, 18, 14, 12, 15, 17, 19];
                $('.dynamicbar1').sparkline(myvalues1, {
                    type: 'bar',
                    barColor: '#159077',
                    barWidth: 4,
                    barSpacing: 1,
                    height: '28px'
                });
                $('.dynamicbar2').sparkline(myvalues2, {
                    type: 'bar',
                    barColor: '#00699e',
                    barWidth: 4,
                    barSpacing: 1,
                    height: '28px'
                });
                $('.dynamicbar3').sparkline(myvalues3, {
                    type: 'bar',
                    barColor: '#9e494e',
                    barWidth: 4,
                    barSpacing: 1,
                    height: '28px'
                });
            };


            //******************************** CHAT MENU SIDEBAR ******************************//
            function chatSidebar() {

                /* Manage the right sidebar */
                if ($.fn.mmenu) {
                    var $menu = $('nav#menu-right');
                    $menu.mmenu({
                        position: 'right',
                        dragOpen: true,
                        counters: false,
                        searchfield: {
                            add: true,
                            search: true,
                            showLinksOnly: false
                        }
                    });
                }

                /* Open / Close right sidebar */
                $('#chat-toggle').on('click', function () {
                    $menu.hasClass('mm-opened') ? $menu.trigger("close") : $menu.trigger("open");
                    $('#chat-notification, #chat-popup').hide();
                    setTimeout(function () {
                        $('.mm-panel .badge-danger').each(function () {
                            $(this).removeClass('hide').addClass('animated bounceIn');
                        });
                    }, 1000);
                });

                /* Remove current message when opening */
                $('.have-message').on('click', function () {
                    $(this).removeClass('have-message');
                    $(this).find('.badge-danger').fadeOut();
                });

                /* Send messages */
                $('.send-message').keypress(function (e) {
                    if (e.keyCode == 13) {
                        var chat_message = '<li class="img">' +
                            '<span>' +
                            '<div class="chat-detail chat-right">' +
                            '<img src="img/avatars/avatar1.png" data-retina-src="img/avatars/avatar1_2x.png"/>' +
                            '<div class="chat-detail">' +
                            '<div class="chat-bubble">' +
                            $(this).val() +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</span>' +
                            '</li>';
                        $(chat_message).hide().appendTo($(this).parent().parent()).fadeIn();
                        $(this).val("");
                    }
                });
            }
            
            /****  Initiation of Main Functions  ****/
            jQuery(document).ready(function () {

                manageSidebar();
                toggleSidebarMenu();
                chatSidebar();
                //customScroll();
                //liveTile();
                //handleSlider();

            });


            /****  On Resize Functions  ****/
            var sidebarTimeOut;
            $("#sidebar").bind("resize", function (e) {
                clearTimeout(sidebarTimeOut);
                sidebarTimeOut = setTimeout(function () {
                    sidebarHeight();
                }, 250);
            });

            (new Home()).showMainDashboard();

        },
        addMenuHandlers: function () {
            var that = this;

            //var $sidebar = this.$sidebar;

            this.$sidebar.find("li").on("click", function (e) {
                e.stopImmediatePropagation();

                var $t = $(e.currentTarget);
                var option = $t.attr("data-roleview");
                var $liParent = $t.parents("li");

                if (option == undefined || option == "" || $t.hasClass("hasSub")) {

                } else {
                    // reset currents
                    $("#sidebar li").removeClass("current");
                    // it is a selectable item
                    $t.addClass("current");

                    // si el parent es un agrupador, marcarlo como current
                    if ($liParent.hasClass("hasSub")) {
                        $liParent.addClass("current");
                    }
                    that.changeView(option, $("#main-content"));
                }
            });

            // VER BIEN ESTE
            // Eventos para los botones AddNew
            /*this.$sidebar.find("ul li span.add_item").on("click", function (e) {
                var $target = $(e.currentTarget);

                //this.$sidebar.find("li.selectable, li.first_level").removeClass("current");
                this.$sidebar.find("li").removeClass("current");

                $target.closest("li").addClass("current");
                if (!$target.closest("li").hasClass("first_level")) {
                    $target.closest("li").parent().closest("li").addClass("current");
                }

                e.preventDefault();
                e.stopImmediatePropagation();
                var option = $target.attr("data-roleview");

                that.changeView(option, $("#main-content"));
                //var element = "main-content";
                //that.changeView(option, element);
            }.bind(that));*/

            this.$sidebar.on("removeMainContent", clearContent($("#main-content")));

            // TO DO REMOVER ESTO
            //require(['controllers/crud/projectMngr'], function (Controller) {
            //    (new Controller()).showEdit($("#main-content"), 1);
            //});


        },
        changeView: function (option, element) {
            clearContent($("#main-content"), function () {
                (new SidebarMngr).addView(option, element);
            });
        }
    });
    return View;
});